package com.dxd.onlineshop.service.impl;

import com.dxd.onlineshop.mapper.UserMapper;
import com.dxd.onlineshop.pojo.Order;
import com.dxd.onlineshop.pojo.OrderItem;
import com.dxd.onlineshop.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private UserMapper userMapper;

    //创建订单
    @Override
    @Transactional
    public Order createOrder(Integer userId, List<OrderItem> orderItems) {
        //创建订单对象
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNumber(generateOrderNumber(userId));
        order.setOrderStatus(Order.OrderStatus.待付款);
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        BigDecimal totalAmount = BigDecimal.ZERO;

        //计算应付金额
        for (OrderItem item : orderItems) {
            totalAmount = totalAmount.add(item.getSubtotal());
        }
        order.setTotalAmount(totalAmount);
        userMapper.createOrder(order);

        //设置订单项
        for (OrderItem item : orderItems) {
            //为每个订单项设置所属订单
            item.setOrderId(order.getOrderId());
            //把订单项添加到订单
            userMapper.addOrderItem(item);
        }
        return order;
    }

    //获取用户订单信息
    @Override
    public List<Order> getUserOrders(Integer userId) {
        return userMapper.getUserOrders(userId);
    }

    //获取订单信息(通过订单ID)
    @Override
    public Order getOrderById(Integer orderId) {
        return userMapper.getOrderById(orderId);
    }

    //更新订单状态
    @Override
    @Transactional
    public boolean updateOrderStatus(Integer orderId, Order.OrderStatus newStatus) {
        Order order = userMapper.getOrderById(orderId);
        if (order == null) {
            return false;
        }
        order.setOrderStatus(newStatus);
        order.setUpdatedAt(LocalDateTime.now());
        return userMapper.updateOrderStatus(orderId, newStatus, order.getUpdatedAt()) > 0;
    }

    //取消订单
    @Override
    @Transactional
    public boolean cancelOrder(Integer orderId) {
        Order order = userMapper.getOrderById(orderId);
        if (order == null || order.getOrderStatus() != Order.OrderStatus.待付款) {
            return false;
        }
        return updateOrderStatus(orderId, Order.OrderStatus.已取消);
    }

    //删除订单
    @Override
    @Transactional
    @SuppressWarnings("NonAsciiCharacters")
    public boolean deleteOrder(Integer orderId) {
        // 1. 首先获取订单信息
        Order order = userMapper.getOrderById(orderId);
        if (order == null) {
            // 订单不存在
            return false;
        }

        // 2. 检查订单状态，只允许删除某些状态的订单（例如：已取消、已完成）
        if (order.getOrderStatus() != Order.OrderStatus.已取消 &&
                order.getOrderStatus() != Order.OrderStatus.已完成) {
            // 订单状态不允许删除
            return false;
        }

        // 3. 删除订单项
        int deletedItems = userMapper.deleteOrderItems(orderId);
        if (deletedItems == 0) {
            // 没有删除任何订单项，可能是因为订单项已经被删除
            // 记录日志或者进行其他处理
            log.info("没有删除任何订单项，可能是因为订单项已经被删除");
        }

        // 4. 删除订单
        int deletedOrder = userMapper.deleteOrder(orderId);

        // 5. 返回删除结果
        return deletedOrder > 0;
    }

    //获取订单统计信息
    @Override
    public OrderStatistics getOrderStatistics(Integer userId) {
        List<Order> orders = getUserOrders(userId);
        int totalOrders = orders.size();
        BigDecimal totalAmount = orders.stream()
                .map(Order::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        OrderStatistics statistics = new OrderStatistics();
        statistics.setTotalOrders(totalOrders);
        statistics.setTotalAmount(totalAmount);
        return statistics;
    }

    //生成订单号
    private String generateOrderNumber(Integer userId) {
        // 生成包含更多信息的订单号，例如：日期 + 用户ID + 随机数
        String dateStr = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        String randomStr;
        randomStr = String.format("%04d", new Random().nextInt(10000));
        return String.format("%s%d%s", dateStr, userId, randomStr);
    }
}